'use client';
import type { NextPage } from 'next';
import { useRouter } from 'next/navigation';
import { useActions, useGlobalState } from '@/hooks';

import { useMemo, useState } from 'react';
import { Card } from '@mui/material';
import Image from 'next/image';
import { createLogger } from '@/utils/front';

import ProductList from './components/ProductList';
import { getAuthorList } from '@/services';
import useMounted from '@/hooks/useMounted';
import Link from 'next/link';
import {
  getAppConfigSA,
  getAuthorListSA,
  getServerSideCategories,
} from '@/services/back';
// import Head from 'next/head';

async function getData() {
  const res = await fetch(
    'https://api.airoxy.com.au/configcenter/api/app/config?appid=2&env=production',
    {
      headers: {
        'sec-ch-ua':
          '"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'x-app-secret': '8d121dc1072dfc9fa2a8aa28fcbf9b6a',
      },
      body: null,
      method: 'GET',
    }
  );

  if (!res.ok) {
    throw new Error('An error occurred while fetching the data');
  }

  return res.json();
}

const homeLogger = createLogger('Home');

const TestPage: NextPage = () => {
  const [authorList, setAuthorList] = useState([] as any[]);
  const [count, setCount] = useState(10086);

  const router = useRouter();

  const userInfo = useGlobalState('user', 'userInfo');
  const { categoryList } = useGlobalState('product');
  const { setUserInfo } = useActions();

  const top10Categories = useMemo(() => {
    return categoryList.slice(0, 10);
  }, [categoryList]);

  homeLogger.info('home page rendered');

  const changeUser = () => {
    setUserInfo({
      name: userInfo.name.replace(/\d+$/, '') + Math.floor(Math.random() * 100),
    });
  };

  useMounted(() => {
    homeLogger.info('home mounted...');
    getData().then(data => {
      homeLogger.info('🚀 getData:', data);
    });
  });

  const fetchAuthorList = async () => {
    const data = await getAuthorList();
    if (data) {
      setAuthorList(data);
    }
  };

  const getAppConfig = async () => {
    const { data: config } = await getAppConfigSA();
  };

  const getAuthors = async () => {
    const { data } = await getAuthorListSA();
  };

  return (
    <div className="home-page overflow-hidden line-height-2">
      <h1 className="ta-c fs30">
        <Image
          className="dis-ib mr10"
          src="/static/images/logo.png"
          alt="1ogo"
          width={30}
          height={30}
        />
        home page
      </h1>

      <hr className="m-4" />
      <div className="ta-c fs20">Test Link</div>
      <Link href="/about">Go About Us</Link>

      <hr className="m-4" />
      <div className="ta-c fs20">Test env variable</div>
      <div>NEXT_PUBLIC_ENV_DEFAULT : {process.env.NEXT_PUBLIC_ENV_DEFAULT}</div>
      <div>NEXT_PUBLIC_ENV_LOCAL : {process.env.NEXT_PUBLIC_ENV_LOCAL}</div>
      <div>NEXT_PUBLIC_ENV_DEV : {process.env.NEXT_PUBLIC_ENV_DEV}</div>
      <div>NEXT_PUBLIC_ENV_PROD : {process.env.NEXT_PUBLIC_ENV_PROD}</div>
      <div className="mt-4"></div>
      <div>NEXT_PUBLIC_ENV_TEST : {process.env.NEXT_PUBLIC_ENV_TEST}</div>
      <div className="mt-4"></div>
      <div>NEXT_PUBLIC_APP_ENV : {process.env.NEXT_PUBLIC_APP_ENV}</div>

      <hr className="m-4" />
      <div className="ta-c fs20">Test redux</div>
      <div>
        store user name: <i>{userInfo.name}</i>
      </div>
      <button className="mr-10" onClick={changeUser}>
        change user
      </button>

      <hr className="m-4" />
      <div className="ta-c fs20">Test State</div>
      <div>count: {count}</div>
      <button className="mr-10" onClick={() => setCount(count + 1)}>
        add count
      </button>

      <hr className="m-4" />
      <div className="ta-c fs20">Test access DB and route handler</div>
      <button onClick={fetchAuthorList}>get authors</button>
      <div className="author-list">authors:</div>
      <ul>
        {authorList.map((item: any) => (
          <li className="flex" key={item.id}>
            <div className="mr-10">{item.name}</div>
            <div className="mr-10">{item.email}</div>
          </li>
        ))}
      </ul>

      <hr className="m-4" />
      <div className="ta-c fs20">Test Server Action</div>
      <form action={getServerSideCategories}>
        <p>Test Server Action:</p>
        <button type="submit">get categories</button>
      </form>
      <button className="m-10" onClick={getAppConfig}>
        get app config
      </button>
      <button className="m-10" onClick={getAuthors}>
        get author list
      </button>

      <hr className="m-4" />
      <div className="ta-c fs20">Test UI Lib</div>
      <Card className="w-1/2 mx-auto mt-10" sx={{ border: '2px solid blue' }}>
        Test Mui component: using a Card
      </Card>
      <div className="test-tail-wind w-1/2 mx-auto mt-10 bg-blue-500">
        Test Tail wind
      </div>

      <hr className="m-4" />
      <div className="ta-c fs20">Test read store categories</div>
      <div className="category-list">
        {categoryList.slice(0, 5).map((item: any) => (
          <div key={item.title}>{item.title}</div>
        ))}
      </div>

      <hr className="m-4" />
      <div className="ta-c fs20">Test import child component</div>
      <ProductList />

      <hr className="m-4" />
      <div className="ta-c fs20">Test useMemo run on server</div>
      {top10Categories.map((item: any) => (
        <div key={item.title}>{item.title}</div>
      ))}
    </div>
  );
};

export default TestPage;
